<template>
  <view class="monthly-card-records-page page-content">
    <z-paging ref="paging" v-model="currentList" @query="queryList" :auto="true" :refresher-enabled="true"
      :loading-more-enabled="true" empty-view-text="暂无数据">
      <template #top>
        <up-navbar title="月卡购买记录" @leftClick="handleBack" :fixed="true" bgColor="transparent" :border="false" placeholder>
          <template>
            <view></view>
          </template>
        </up-navbar>

        <up-sticky class="padding-20" bgColor="transparent">
          <!-- 筛选条件 -->
          <view class="filter-section">
            <!-- 车牌号搜索 -->
            <view class="filter-item">
              <up-search v-model="searchForm.plateNumber" :clearabled="true" :showAction="true" 
                placeholder="请输入车牌号" @search="handleSearch" @clear="handleClear">
                <template #action>
                  <up-button type="primary" size="small" @click="handleSearch">搜索</up-button>
                </template>
              </up-search>
            </view>
            
            <!-- 状态筛选 -->
            <view class="filter-item">
              <up-dropdown>
                <up-dropdown-item v-model="searchForm.status" title="状态筛选" :options="statusOptions" @change="handleStatusChange" />
              </up-dropdown>
            </view>
          </view>
        </up-sticky>
      </template>

      <!-- 列表内容 -->
      <view class="monthly-card-records-list">
        <view class="list-item-card" v-for="(item, index) in currentList" :key="index">
          <view class="card-header">
            <view class="title">
              车牌号：<text class="number">{{ item.plateNumber }}</text>
            </view>
            <view class="status" :class="getStatusClass(item.status)">{{ item.statusText }}</view>
          </view>
          <view class="card-content-box">
            <view class="content">
              <view class="item">
                <text class="label">购买时间：</text>
                <text class="value">{{ item.purchaseTime }}</text>
              </view>
              <view class="item">
                <text class="label">购买金额：</text>
                <text class="value amount">¥{{ item.amount }}</text>
              </view>
              <view class="item">
                <text class="label">购买用户：</text>
                <text class="value">{{ item.userName }}</text>
              </view>
              <view class="item">
                <text class="label">月卡信息：</text>
                <text class="value">{{ item.cardInfo }}</text>
              </view>
              <view class="item">
                <text class="label">月租车有效期：</text>
                <text class="value">{{ item.validPeriod }}</text>
              </view>
              <view class="item">
                <text class="label">每天免费时间：</text>
                <text class="value">{{ item.freeHoursPerDay }}小时</text>
              </view>
            </view>
            <view class="card-footer">
              <view class="operate">
                <up-button type="primary" text="查看详情" class="custom-style" @click.stop="viewRecordDetail(item)"></up-button>
              </view>
            </view>
          </view>
        </view>
      </view>
    </z-paging>

    <!-- 详情弹窗 -->
    <up-popup :show="showDetailModal" mode="center" round="10" @close="showDetailModal = false" width="90%">
      <view class="detail-modal" v-if="selectedRecord">
        <view class="modal-title">购买记录详情</view>
        <view class="modal-content">
          <view class="detail-item">
            <text class="detail-label">车牌号：</text>
            <text class="detail-value">{{ selectedRecord.plateNumber }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">状态：</text>
            <text class="detail-value" :class="'record-' + getStatusClass(selectedRecord.status)">{{ selectedRecord.statusText }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">购买时间：</text>
            <text class="detail-value">{{ selectedRecord.purchaseTime }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">购买金额：</text>
            <text class="detail-value amount">¥{{ selectedRecord.amount }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">购买用户：</text>
            <text class="detail-value">{{ selectedRecord.userName }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">月卡信息：</text>
            <text class="detail-value">{{ selectedRecord.cardInfo }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">月租车有效期：</text>
            <text class="detail-value">{{ selectedRecord.validPeriod }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">每天免费时间：</text>
            <text class="detail-value">{{ selectedRecord.freeHoursPerDay }}小时</text>
          </view>
        </view>
        <view class="modal-footer">
          <up-button type="primary" text="关闭" @click="showDetailModal = false"></up-button>
        </view>
      </view>
    </up-popup>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';

// 搜索表单
const searchForm = reactive({
  plateNumber: '', // 车牌号
  status: '' // 状态筛选
});

// 状态选项
const statusOptions = [
  { label: '全部', value: '' },
  { label: '正常', value: 'normal' },
  { label: '即将过期', value: 'expiring' },
  { label: '未开始', value: 'notStarted' },
  { label: '禁用', value: 'disabled' },
  { label: '已过期', value: 'expired' }
];

// z-paging 组件引用
const paging = ref(null);

// 当前列表数据
const currentList = ref([]);

// 选中的记录
const selectedRecord = ref(null);

// 详情弹窗
const showDetailModal = ref(false);

// 处理搜索
const handleSearch = () => {
  paging.value.reload();
};

const handleBack = () => {
  uni.redirectTo({
    url: '/pages/home/index'
  })
}

// 处理清除
const handleClear = () => {
  searchForm.plateNumber = '';
  searchForm.status = '';
  paging.value.reload();
};

// 处理状态变更
const handleStatusChange = () => {
  paging.value.reload();
};

// 查看记录详情
const viewRecordDetail = (record) => {
  selectedRecord.value = record;
  showDetailModal.value = true;
  console.log('查看购买记录详情:', record.plateNumber);
};

// 获取状态样式类
const getStatusClass = (status) => {
  switch (status) {
    case 'normal': return 'status-normal';
    case 'expiring': return 'status-expiring';
    case 'notStarted': return 'status-not-started';
    case 'disabled': return 'status-disabled';
    case 'expired': return 'status-expired';
    default: return '';
  }
};

// 生成随机车牌号
const generateRandomPlateNumber = () => {
  const provinces = ['粤', '京', '沪', '津', '渝', '冀', '豫', '云', '辽', '黑', '湘', '皖', '鲁', '苏', '浙', '赣', '鄂', '桂', '甘', '晋', '蒙', '陕', '吉', '闽', '贵', '粤', '川', '青', '藏', '琼', '宁', '新'];
  const letters = 'ABCDEFGHJKLMNPQRSTUVWXYZ';
  const province = provinces[Math.floor(Math.random() * provinces.length)];
  const letter = letters[Math.floor(Math.random() * letters.length)];
  const numbers = Math.floor(Math.random() * 100000).toString().padStart(5, '0');
  return `${province}${letter}${numbers}`;
};

// 生成模拟列表数据
const generateMockList = (pageNo, pageSize) => {
  // 生成基础数据
  const baseList = Array.from({ length: pageSize }, (_, i) => {
    // 状态定义
    const statusTypes = ['normal', 'expiring', 'notStarted', 'disabled', 'expired'];
    const statusWeights = [0.5, 0.2, 0.1, 0.1, 0.1]; // 权重分配，正常状态占比更高
    
    // 根据权重随机选择状态
    let statusIndex = 0;
    const random = Math.random();
    let cumulativeWeight = 0;
    
    for (let j = 0; j < statusWeights.length; j++) {
      cumulativeWeight += statusWeights[j];
      if (random < cumulativeWeight) {
        statusIndex = j;
        break;
      }
    }
    
    const status = statusTypes[statusIndex];
    
    // 状态文本映射
    const statusTextMap = {
      normal: '正常',
      expiring: '即将过期',
      notStarted: '未开始',
      disabled: '禁用',
      expired: '已过期'
    };
    
    // 生成随机车牌号
    const plateNumber = generateRandomPlateNumber();
    
    // 生成随机有效期
    const now = new Date();
    let startDate, endDate;
    
    if (status === 'notStarted') {
      // 未开始状态：开始日期在未来
      startDate = new Date(now.getTime() + Math.random() * 30 * 24 * 60 * 60 * 1000);
      endDate = new Date(startDate.getTime() + (Math.floor(Math.random() * 12) + 1) * 30 * 24 * 60 * 60 * 1000);
    } else if (status === 'expired') {
      // 已过期状态：结束日期在过去
      endDate = new Date(now.getTime() - Math.random() * 30 * 24 * 60 * 60 * 1000);
      startDate = new Date(endDate.getTime() - (Math.floor(Math.random() * 12) + 1) * 30 * 24 * 60 * 60 * 1000);
    } else if (status === 'expiring') {
      // 即将过期状态：结束日期在未来7天内
      endDate = new Date(now.getTime() + Math.random() * 7 * 24 * 60 * 60 * 1000);
      startDate = new Date(endDate.getTime() - (Math.floor(Math.random() * 12) + 1) * 30 * 24 * 60 * 60 * 1000);
    } else {
      // 其他状态：正常有效期
      startDate = new Date(now.getTime() - Math.random() * 30 * 24 * 60 * 60 * 1000);
      endDate = new Date(startDate.getTime() + (Math.floor(Math.random() * 12) + 1) * 30 * 24 * 60 * 60 * 1000);
    }
    
    const formatDate = (date) => {
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
    };
    
    const validPeriod = `${formatDate(startDate)} 至 ${formatDate(endDate)}`;
    
    // 生成随机每日免费时长
    const freeHoursPerDay = Math.floor(Math.random() * 12) + 1;
    
    // 应用筛选条件
    if (searchForm.plateNumber && !plateNumber.includes(searchForm.plateNumber)) {
      return null; // 不符合车牌号筛选条件
    }
    
    if (searchForm.status && status !== searchForm.status) {
      return null; // 不符合状态筛选条件
    }
    
    // 返回列表项数据
    return {
      id: (pageNo - 1) * pageSize + i + 1,
      plateNumber,
      status,
      statusText: statusTextMap[status],
      purchaseTime: `2023-${Math.floor(Math.random() * 12) + 1}-${Math.floor(Math.random() * 28) + 1} ${Math.floor(Math.random() * 24).toString().padStart(2, '0')}:${Math.floor(Math.random() * 60).toString().padStart(2, '0')}`,
      amount: (Math.random() * 500 + 100).toFixed(2),
      userName: `用户${Math.floor(Math.random() * 1000) + 1}`,
      cardInfo: `${Math.floor(Math.random() * 12) + 1}个月月卡`,
      validPeriod,
      freeHoursPerDay
    };
  }).filter(item => item !== null); // 过滤掉不符合筛选条件的项
  
  return baseList;
};

// 查询列表数据
const queryList = async (pageNo, pageSize) => {
  try {
    // 处理搜索参数
    const params = {
      pageNo,
      pageSize,
      plateNumber: searchForm.plateNumber,
      status: searchForm.status
    };
    
    // 模拟API调用
    // 实际项目中应替换为真实API
    // const result = await getMonthlyCardRecords(params);
    // const data = result.data;
    
    // 模拟数据
    const mockData = {
      total: 100,
      list: generateMockList(pageNo, pageSize)
    };
    
    // 通知z-paging组件数据加载完成
    paging.value.complete(mockData.list);
  } catch (error) {
    console.error('获取月卡购买记录数据失败:', error);
    paging.value.complete(false);
  }
};

// 页面加载时初始化数据
onMounted(() => {
  // 初始化加载数据
  queryList(1, 10);
});
</script>

<style lang="scss" scoped>
.monthly-card-records-page {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.filter-section {
  padding: 20rpx;
  background-color: #fff;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
}

.filter-item {
  margin-bottom: 20rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.monthly-card-records-list {
  padding: 0 15px;
}

.list-item-card {
  &:active {
    transform: scale(0.98);
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px;
    border-bottom: 1px solid #f0f0f0;
    
    .title {
      font-size: 14px;
      color: #333;
      
      .number {
        font-weight: 600;
        color: #000;
      }
    }
    
    .status {
      padding: 4px 10px;
      border-radius: 15px;
      font-size: 12px;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }
    
    .status-normal {
      background-color: #e1f3d8;
      color: #67c23a;
    }
    
    .status-expiring {
      background-color: #fdf6ec;
      color: #e6a23c;
    }
    
    .status-not-started {
      background-color: #e9f4fe;
      color: #409eff;
    }
    
    .status-disabled {
      background-color: #f4f4f5;
      color: #909399;
    }
    
    .status-expired {
      background-color: #fef0f0;
      color: #f56c6c;
    }
  }
  
  .card-content-box {
    padding: 15px;
    
    .content {
      .item {
        display: flex;
        margin-bottom: 10px;
        font-size: 14px;
        
        .label {
          color: #666;
          min-width: 100px;
        }
        
        .value {
          color: #333;
          flex: 1;
          
          &.amount {
            color: #f56c6c;
            font-weight: 500;
          }
        }
      }
    }
  }
}

.detail-modal {
  padding: 20px;
  
  .modal-title {
    font-size: 18px;
    font-weight: 600;
    color: #333;
    text-align: center;
    margin-bottom: 20px;
    position: relative;
    
    &::after {
      content: '';
      position: absolute;
      bottom: -10px;
      left: 50%;
      transform: translateX(-50%);
      width: 50px;
      height: 3px;
      background-color: #409eff;
      border-radius: 3px;
    }
  }
  
  .modal-content {
    margin-bottom: 20px;
    
    .detail-item {
      display: flex;
      margin-bottom: 15px;
      font-size: 14px;
      
      .detail-label {
        color: #666;
        min-width: 100px;
      }
      
      .detail-value {
        color: #333;
        flex: 1;
        
        &.amount {
          color: #f56c6c;
          font-weight: 500;
        }
      }
      
      .record-status-normal {
        color: #67c23a;
      }
      
      .record-status-expiring {
        color: #e6a23c;
      }
      
      .record-status-not-started {
        color: #409eff;
      }
      
      .record-status-disabled {
        color: #909399;
      }
      
      .record-status-expired {
        color: #f56c6c;
      }
    }
  }
  
  .modal-footer {
    display: flex;
    justify-content: center;
  }
}
</style>